package com.daichi.security;

import cn.hutool.core.util.StrUtil;
import com.daichi.common.exception.CaptchaException;
import com.daichi.common.lang.Const;
import com.daichi.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CaptchaFilter extends OncePerRequestFilter {

    private final RedisUtil redisUtil;

    private final LoginFailureHandler loginFailureHandler;

    @Autowired
    public CaptchaFilter(RedisUtil redisUtil, LoginFailureHandler loginFailureHandler) {
        this.redisUtil = redisUtil;
        this.loginFailureHandler = loginFailureHandler;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String url = request.getRequestURI();

        if ("/login".equals(url) && "POST".equals(request.getMethod())) {
            // 校验验证码
            try {
                validate(request);
            } catch (AuthenticationException e) {
                // 如果不正确就跳转到认证失败处理器
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        filterChain.doFilter(request, response);
    }

    private void validate(HttpServletRequest request) {

        String code = request.getParameter("code");
        String key = request.getParameter("token");

        if (StrUtil.isBlank(code) || StrUtil.isBlank(key)) {
            throw new CaptchaException("验证码错误");
        }

        String cachedCode = (String) redisUtil.hget(Const.REDIS_CAPTCHA_KEY, key);

        if (StrUtil.isBlank(cachedCode)) {
            throw new CaptchaException("请刷新验证码重试");
        }

        if (!code.equals(cachedCode)) {
            throw new CaptchaException("验证码错误");
        }

        redisUtil.hdel(Const.REDIS_CAPTCHA_KEY,key);
    }
}
